﻿using NAudio.Wave;

namespace NAudio.WpfApp;

public class Recorder
{
    //public WaveIn mWaveIn;  // 这个是纯麦克风的声音
    public WasapiLoopbackCapture mWaveIn; // 这个是声卡输出，也就是当前播放的声音。
    public WaveFileWriter mWaveFileWriter;
    public int secondsRecorder;

    public void RecorderStart(string filePath)
    {
        mWaveIn = new WasapiLoopbackCapture();
        mWaveIn.DataAvailable += OnDataAvailable;

        mWaveFileWriter = new WaveFileWriter(filePath, mWaveIn.WaveFormat);
        mWaveIn.StartRecording();
    }

    public void RecorderStop()
    {
        mWaveIn?.StopRecording();
        mWaveIn?.Dispose();
        mWaveFileWriter?.Close();
        mWaveFileWriter = null;
    }

    private void OnDataAvailable(object? sender, WaveInEventArgs e)
    {
        mWaveFileWriter.Write(e.Buffer, 0, e.BytesRecorded);
        secondsRecorder = (int)mWaveFileWriter.Length / mWaveFileWriter.WaveFormat.AverageBytesPerSecond;
    }
}